#!/bin/bash
#############################
##常用自定义方法
#############################


#替换文件中字符所在行内容
#用法：str_replace_file "^;date.timezone =" "date.timezone = \"Asia/Shanghai\"" "/home/php.ini"
function str_replace_file(){
	line_str=`grep -n "$1" $3`
	OLD_IFS="$IFS"
	IFS=":"
	arr=($line_str)
	IFS="$OLD_IFS"
	line_num=${arr[0]}
	new_str="$2"
	if [ "$line_num" > "0" ]; then
		sed -i "${line_num} d" "$3"
		sed -i "${line_num} i${new_str}" "$3"
	fi
}

#在文件中指定字符串行的下一行增加内容
#用法：str_after_add_file "^date.timezone =" "add test" "/home/php.ini"
function str_after_add_file(){
	line_str=`grep -n "$1" $3`
	OLD_IFS="$IFS"
	IFS=":"
	arr=($line_str)
	IFS="$OLD_IFS"
	line_num=${arr[0]}
	add_str="$2"
	if [ "$line_num" > "0" ]; then
		sed -i "N;${line_num}a${add_str}" "$3"
	fi
}

#在文件中指定字符串行的上一行增加内容
#用法：str_before_add_file "^date.timezone =" "add test" "/home/php.ini"
function str_before_add_file(){
	line_str=`grep -n "$1" $3`
	OLD_IFS="$IFS"
	IFS=":"
	arr=($line_str)
	IFS="$OLD_IFS"
	line_num=${arr[0]}
	add_str="$2"
	if [ "$line_num" > "0" ]; then
		sed -i "N;${line_num}i${add_str}" "$3"
	fi
}

#字符串分割成字符串数组
#用法：result=($(str_split "hello,world,nice,to,meet,you" ",")); echo ${result[2]}
function str_split(){
	str="$1"
	OLD_IFS="$IFS" 
	IFS="$2"
	arr=($str)    #如下会自动分隔
	IFS="$OLD_IFS"
	echo ${arr[*]}
}

#数组去重复值
#用法：array=("hello" "world" "nice" "to" "meet" "you" "hello" "to");
#	   result=($(array_unique "${array[*]}")); echo "所有参数：${result[*]}";
function array_unique(){
	arr=$1
	arr=($(awk -v RS=' ' '!a[$1]++' <<< $arr))
	echo ${arr[*]}
}



